package com.joy.ogljoy_01.opengl.util;

import java.io.IOException;
import java.io.InputStream;

import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.Paint;

import com.joy.ogljoy_01.OpenGLView;

public class BitmapUtil {
	public static final Config DEFAULT = Config.ARGB_8888;
	public static final Config ALPHA = Config.RGB_565;

	public static Bitmap makeBitmapFromResourceById(int id) {
		InputStream is = OpenGLView.app.getResources().openRawResource(id);

		return makeBitmapByInputStream(is);
	}
	
	public static Bitmap makeBitmapFromAssets(String name) {
		Bitmap bitmap = null;
		try {
			InputStream is = OpenGLView.app.getAssets().open(name);
			bitmap = makeBitmapByInputStream(is);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return bitmap;
	}
	
	public static Bitmap makeBitmapByInputStream(InputStream is) {
		Bitmap bitmap = null;
		if(is != null) {
			bitmap = BitmapFactory.decodeStream(is);
			try {
				is.close();
			} catch (IOException e) {
				// Ignore.
			} finally {
				if(is != null) {
					is = null;
				}
			}
		}

		return bitmap;
	}
	
	/**
	 * 修整图片到最小2次方的大小
	 * @param bmp
	 * @return
	 */
    public static Bitmap fixPow2Bitmap(Bitmap bmp) { 
        int mWidth = bmp.getWidth(); 
        int mHeight = bmp.getHeight(); 
        int mPow2Width = Utils.roundUpPower2(mWidth); 
        int mPow2Height = Utils.roundUpPower2(mHeight); 
        
    	Bitmap bitmap = Bitmap.createBitmap(mPow2Width, mPow2Height, 
    			bmp.hasAlpha() ? DEFAULT : ALPHA); 
        Canvas canvas = new Canvas(bitmap); 
        canvas.drawBitmap(bmp, 0, 0, null); 
        bmp.recycle();
        bmp = null;
        
        return  bitmap; 
    }
    
//    public static int pow2(int size) { 
//        int small = (int)(Math.log((double)size)/Math.log(2.0f)) ; 
//        if ( (1 << small) >= size) {
//            return 1 << small; 
//        } else {
//            return 1 << (small + 1);
//        }
//    }
	
	/**
	 * 图片置灰
	 */
	public static Bitmap grayBitmap(Bitmap bmp) {
		Bitmap grayBmp = Bitmap.createBitmap(bmp.getWidth(), bmp.getHeight(), 
    			bmp.hasAlpha() ? DEFAULT : ALPHA);
		Paint paint = new Paint();
		ColorMatrix colorMatrix = new ColorMatrix();
        colorMatrix.setSaturation(0);
        ColorMatrixColorFilter colorMatrixFilter = new ColorMatrixColorFilter(colorMatrix);
        paint.setColorFilter(colorMatrixFilter);
		Canvas cav = new Canvas(grayBmp);
		cav.drawBitmap(bmp, 0, 0, paint);
		bmp.recycle();
		bmp = null;
		return grayBmp;
	}
}
